// main.go
package controller

import (
	"encoding/json"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type Memo struct {
	ID        string      `json:"id"`
	Title     string      `json:"title"`
	Content   string      `json:"content"`
	Tags      []string    `json:"tags"`
	Category  string      `json:"category"`
	CreatedAt time.Time   `json:"createdAt"`
	UpdatedAt time.Time   `json:"updatedAt"`
	Reminders []time.Time `json:"reminders,omitempty"`
}

type MemoApp struct {
	Base
	memos      []Memo
	categories []string
	dataPath   string
	mu         sync.Mutex
}

func NewMemoApp() *MemoApp {
	app := &MemoApp{
		memos:      make([]Memo, 0),
		categories: []string{"工作", "个人", "学习", "其他"},
	}
	app.dataPath = filepath.Join(app.getAppPath(), "memos.json")
	app.loadData()
	return app
}

func (a *MemoApp) LoadMemos() []Memo {
	a.mu.Lock()
	defer a.mu.Unlock()
	return a.memos
}

func (a *MemoApp) LoadCategories() []string {
	return a.categories
}

func (a *MemoApp) SaveMemo(memo Memo) (Memo, error) {
	a.mu.Lock()
	defer a.mu.Unlock()

	found := false
	for i, m := range a.memos {
		if m.ID == memo.ID {
			a.memos[i] = memo
			found = true
			break
		}
	}

	if !found {
		a.memos = append(a.memos, memo)
	}

	err := a.saveData()
	if err != nil {
		runtime.LogErrorf(a.ctx, "Failed to save memo: %v", err)
		return Memo{}, err
	}
	return memo, nil
}

func (a *MemoApp) DeleteMemo(id string) error {
	a.mu.Lock()
	defer a.mu.Unlock()

	for i, m := range a.memos {
		if m.ID == id {
			a.memos = append(a.memos[:i], a.memos[i+1:]...)
			break
		}
	}

	return a.saveData()
}

func (a *MemoApp) loadData() error {
	a.mu.Lock()
	defer a.mu.Unlock()

	data, err := os.ReadFile(a.dataPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}

	return json.Unmarshal(data, &a.memos)
}

func (a *MemoApp) saveData() error {
	data, err := json.MarshalIndent(a.memos, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(a.dataPath, data, 0644)
}
